<template>
  <div class="body">
    <el-row :gutter="24" class="box-card">
      <!--   导航栏-->
      <el-col :span="1">
        <Navigation></Navigation>
      </el-col>
      <el-col :span="22" :offset="1">
        <!--  选择框-->
        <el-row>
          <el-col :span="22">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>收入查询</span>
              </div>
              <div>
                <el-row :gutter="18">
                  <el-col :span="6" :offset="2">
                    <span>收入类型</span>
                    <el-select
                        v-model="TypeIncome"
                        clearable
                        style="margin-left: 2%;"
                        placeholder="请选择"
                    >
                      <el-option
                          v-for="item in incomeTypes"
                          :key="item.id"
                          :label="item.name"
                          :value="item.name">
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="11">
                    <DatePicker @returnDate="getDate" type="success"></DatePicker>
                  </el-col>
                  <el-col :span="1">
                    <el-button type="success" @click="queryIncome()">查询</el-button>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <!--   table表格-->
        <el-row :gutter="22" class="box-card">
          <el-col :span="22">
            <el-card class="box-card">
              <div slot="header">
                <span style="padding-right: 6%">收入表格</span>
                <!-- 添加Form -->
                <el-button type="success" round @click="dialogFormVisible = true" icon="el-icon-plus">收入</el-button>
                  <el-dialog title="新增收入" :visible.sync="dialogFormVisible" width="30%">
                  <el-form :model="form" style="margin-left: 20%">
                    <el-form-item label="类型" >
                      <el-select
                          v-model="form.typeIncome"
                          placeholder="请选择"
                          clearable
                          filterable
                          allow-create
                          style="width:210px;">
                        <el-option v-for="item in incomeTypes" :label="item.name" :value="item.name" :key="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="金额">
                      <el-input-number v-model="form.money" controls-position="left" @change="handleChange" :min="1" style="width:210px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="详情" clearable >
                      <el-input v-model="form.comment" style="width:210px;"></el-input>
                    </el-form-item>
                    <el-form-item label="时间" clearable >
                      <el-date-picker
                          v-model="form.createtime"
                          type="datetime"
                          placeholder="选择日期时间"
                          style="width:210px;">
                      </el-date-picker>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelAdd()">取 消</el-button>
                    <el-button type="primary" @click="addIncome()">添 加</el-button>
                  </div>
                </el-dialog>
                <span style="padding-left: 60%">总金额:￥{{ this.moneySum }}</span>
<!--                <span style="position: relative;display:flex;justify-content:end;">总金额：1234￥</span>-->
              </div>
              <div>
                <el-table
                    v-loading="loading"
                    :data="incomeDetails"
                    stripe
                    border
                    height="60vh"
                    size="medium"
                    :default-sort="{prop: 'createtime', order: 'descending'}"
                    style="width:80%;margin-left:10%;"
                >
                  <el-table-column
                      type="index"
                      label="序号"
                      width="80px"
                      align="center"
                      sortable>
                  </el-table-column>
                  <el-table-column
                      prop="createtime"
                      label="日期"
                      sortable>
                  </el-table-column>
                  <el-table-column
                      prop="money"
                      label="金额"
                      sortable>
                  </el-table-column>
                  <el-table-column
                      prop="typeIncome"
                      label="收入类型"
                      sortable>
                  </el-table-column>
                  <el-table-column
                      prop="comment"
                      label="详情">
                  </el-table-column>
                  <el-table-column
                      prop=""
                      label="操作"
                  >
                    <template slot-scope="scope">
                      <el-button
                          size="mini"
                          icon="el-icon-edit"
                          @click="handleEdit(scope.$index,scope.row)">编辑
                      </el-button>
                      <el-popconfirm
                          confirm-button-text='确定'
                          cancel-button-text='不用了'
                          icon="el-icon-delete"
                          icon-color="red"
                          title="确定删除该条记录吗？"
                          @confirm="handleDelete(scope.$index, scope.row)"
                      >
                        <el-button
                            slot="reference"
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            style="margin:5px"
                        >删除
                        </el-button>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
                <!--修改的dialog框-->
                <el-dialog title="新增收入" :visible.sync="editDialogFormVisible" width="30%">
                <el-form :model="form" style="margin-left: 20%">
                  <el-form-item label="类型" >
                    <el-select
                        v-model="form.typeIncome"
                        placeholder="请选择"
                        clearable
                        filterable
                        allow-create
                        style="width:210px;">
                      <el-option v-for="item in incomeTypes" :label="item.name" :value="item.name" :key="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="金额">
                    <el-input-number v-model="form.money" controls-position="left" @change="handleChange" :min="1" style="width:210px;"></el-input-number>
                  </el-form-item>
                  <el-form-item label="详情" clearable >
                    <el-input v-model="form.comment" style="width:210px;"></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="cancelEdit()">取 消</el-button>
                  <el-button type="primary" @click="editIncome()">修 改</el-button>
                </div>
              </el-dialog>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <Footer></Footer>
  </div>
</template>

<script>
import DatePicker from "@/components/DatePicker";
import Footer from '@/components/Footer'
import {mapState} from "vuex";
import {addIncomeDetail, findAllIncome, queryIncome, updateIncome} from "@/api/income";
import {getToken} from '@/plugins/token'
import {getUserInfo} from "@/api/user";
import dayjs from 'dayjs'

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Income",
  components: {DatePicker,Footer},
  data() {
    return {
      TypeIncome: '',
      dialogFormVisible: false,
      form: {
        typeIncome: '',
        money: '',
        comment: '',
        userid: '',
        createtime:"",
      },
      formLabelWidth: '110px',
      //收入记录
      incomeDetails:[],
      //用户id
      userid:0,
      //table 加载效果
      loading: true,
      //token
      token:"",
      //用户信息
      userInfo:{},
      //修改的dialog
      editDialogFormVisible:false,
      //从datepicker获取的数据
      daterange:[],
    }
  },
  async mounted(){
    this.$store.dispatch('incomeTypes')
    this.token=getToken();
    this.userInfo=await getUserInfo(this.token);
    this.userid=this.userInfo.id;
    this.$nextTick(() =>{
      this.getIncome()
    })
  },
  methods: {
    //初始化incomeDetails
    async getIncome(){
      //获取所有收入记录
      const result =await findAllIncome(this.userid);
      //将时间以YYYY-MM-DD HH:mm:ss格式输出展示，否则展示的格式为IOSjson格式
      result.forEach((item)=>{
        item.createtime=dayjs(item.createtime).format("YYYY-MM-DD HH:mm:ss");
      })
      this.incomeDetails=result;
    },
    handleEdit(index, row) {
      //获取form参数
      // this.form={...row};//浅拷贝
      Object.assign(this.form,row);//Cannot convert undefined or null to object
      //editDialogFormVisible的控制先后，后显示保证Dialog里的数据已经更新
      this.editDialogFormVisible=true;
    },
    //修改income记录
    async editIncome(){
      this.editDialogFormVisible=false;
      //由于createtime展示时格式被修改，现复原数据格式
      this.form.createtime=dayjs(this.form.createtime).format();
      //发起数据更新请求
      const result = await updateIncome(this.form);
      if(result == "") {
        this.$message({
          type: 'success',
          message: '编辑成功'
        })
      }
      //重新获取数据,若用户进行了查询操作，则刷新展示的依旧为查询时的数据
      this.queryIncome();
      //清空form
      this.form.typeIncome="";
      this.form.money="";
      this.form.comment="";
      this.form.createtime="";
    },
    //取消修改
    cancelEdit(){
      this.editDialogFormVisible=false;
      //清空form
      this.form.typeIncome="";
      this.form.money="";
      this.form.comment="";
      this.form.createtime="";
    },
    //删除一条收入记录
    async handleDelete(index, row) {
      console.log(index, row);
      //发起删除请求
      const result=await this.$API.default.income.deleteIncome(row.id);
      if(result==true){
        this.$message({
          type:'warning',
          message:'删除成功'
        })
        //刷新表格内容,若用户进行了查询操作，则刷新展示的依旧为查询时的数据
        this.queryIncome();
      }else{
        this.$message({
          type:'error',
          message:result
        })
      }
    },
    handleChange(value) {
      console.log(value);
    },
    //添加一条收入记录
    async addIncome(){
      this.form.userid=this.userid;
      //发起添加收入记录请求
      const result= await addIncomeDetail(this.form);
      if(result==true){
        this.$message({
          type:'success',
          message:'添加成功'
        })
        //刷新表格内容
        this.dialogFormVisible = false;
        //刷新表格内容,若用户进行了查询操作，则刷新展示的依旧为查询时的数据
        this.TypeIncome=this.form.typeIncome;
        this.queryIncome();
        //清除表单from的遗留数据，同时清除搜索词条信息
        this.form.typeIncome="";
        this.form.money="";
        this.form.comment="";
        this.form.createtime="";

      }else{
        this.$message({
          type:'error',
          message:result
        })
      }
      this.dialogFormVisible = false;
    },
    //取消添加
    cancelAdd(){
      this.dialogFormVisible = false;
      //清除表单from的遗留数据
      this.form.typeIncome="";
      this.form.money="";
      this.form.comment="";
      this.form.createtime="";
    },
    //从datepicker获取date
    getDate(value){
      this.daterange=value;
    },
    //查询收入记录
    async queryIncome(){
      //userInfo,typePayout,start,end
      const {userInfo,TypeIncome,daterange} =this
      //dayjs('0000-00-00 00:00:00').format(1899-11-30 00:00:00
      let start=daterange[0]==undefined?dayjs('0000-00-00 00:00:00').format("YYYY-MM-DD HH:mm:ss"):dayjs(daterange[0]).format("YYYY-MM-DD HH:mm:ss");
      let end=dayjs(daterange[1]).format("YYYY-MM-DD HH:mm:ss");
      let type=TypeIncome==""?'empty':TypeIncome;

      const result= await queryIncome(userInfo,type,start,end);
      //将时间以YYYY-MM-DD HH:mm:ss格式输出展示，否则展示的格式为ISO-8601 json格式
      result.forEach((item)=>{
        item.createtime=dayjs(item.createtime).format("YYYY-MM-DD HH:mm:ss");
      })
      this.incomeDetails=result;

    }
  },
  computed: {
    ...mapState({
      incomeTypes: (state) => {
        return state.types.incomeTypes;
      }
    }),
    moneySum(){
      let val=0;
      this.incomeDetails.forEach((item)=>{
        val=val+item.money;
      })
      return Math.floor(val*100)/100;
    },
    /*incomeTypes(){//从vuex中取数据的第二种方式
      return this.$store.state.types.incomeTypes;
    },*/
    /*...mapState({
      incomeDetails:(state)=>{
        return state.incomeDetails.incomeDetails;
      }
    })*/
    },
  watch:{
    incomeDetails:{
      handler(){
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
.body {
  background-color: #42b983;
  width: 100%;
  height: 100%;
}

.box-card {
  padding-top: 1%;
}

</style>